/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// @ts-nocheck
import router from '@system.router';
import featureAbility from '@ohos.ability.featureAbility';
import display from '@ohos.display';
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import request from '@ohos.request';
import http from '@ohos.net.http';

const titles = [
    {
        'name': 'All'
    },
    {
        'name': 'Health'
    },
    {
        'name': 'Finance'
    },
    {
        'name': 'Technology'
    },
    {
        'name': 'Sport'
    },
    {
        'name': 'Internet'
    },
    {
        'name': 'Game'
    }
];

const chatData = [
    {
        'title': '名字',
        'topMessage': '吃了没有?',
        'imgUrl': ' ',//我叫学习
        'readTime': '17:00',
        'unRead': '4',
    },
    {
        'title': '萌聊号',
        'topMessage': '这篇文章很好',
        'imgUrl': ' ',//122343423
        'readTime': '17:00',
        'unRead': '1',
    },
    {
        'title': '更多信息',
        'topMessage': '不用谢!',
        'imgUrl': '无',
        'readTime': '17:00',
        'unRead': '2',
    },
];
var personData = {
    'title': '头像',
    'imgUrl': '',
}

export default {
    data: {
        titleList: titles,
        chatList: chatData,
        person:personData,
    },
    onInit() {
//        this.title = this.$t('strings.world');
        console.log('宽度:' + display.width + "高度：" + display.height);
        this.grantPermission()
//        if(router.getParams() != null){ //不需要，先记录一下可实现的方法
//            if(router.getParams().nickname != null){
//                this.chatList[0].imgUrl = router.getParams().nickname;
//            }
//            if(router.getParams().uid != null){
//                this.chatList[1].imgUrl = router.getParams().uid;
//            }
//        }
    },
    /*获取部分权限*/
    grantPermission() {
        console.info('grantPermission')
        let context = featureAbility.getContext()
        context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC','ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA'], 666, function (result) {
            console.info(`grantPermission,requestPermissionsFromUser`);
            console.info('personPage=====requestPermissionsFromUserresult:' + JSON.stringify(result));
        });
    },
    onShow() {
        console.info("personPage=====On show");
        this.getProfileImg(this.$app.$def.uid);
        this.chatList[0].imgUrl = this.$app.$def.nickname
        this.chatList[1].imgUrl = this.$app.$def.uid
    },
    // 选择新闻类型
    changeNewsType: function(e) {
        const type = titles[e.index].name;
        this.chatList = [];
        if (type === 'All') {
            // 展示全部新闻
            this.chatList = chatData;
        } else {
            // 分类展示新闻
            const newsArray = [];
            for (const news of chatData) {
                if (news.type === type) {
                    newsArray.push(news);
                }
            }
            this.chatList = newsArray;
        }
    },
    listTo(title){
        if(title == '名字'){
            router.push({
                uri: "pages/myList/personPage/changeNickname/changeNickname",
            });
        }
    },
    itemClick(chat){
        router.push({
            uri: "pages/dialogPage/dialogPage",
            params: {
                'title': personData.name,
                'type': personData.personNum,
                'imgUrl': personData.imgUrl,
            }
        });
    },
    chat(){
        router.push({
            uri: "pages/sessionList/sessionList",
        });
    },
    message(){
        router.push({
            uri: "pages/mailList/mailList",
        });
    },
    find(){
        router.push({
            uri: "pages/findList/findList",
        });
    },
    backToMy(){
        router.back({
            uri: "pages/index/index",
            params: {
                'title': personData.name,
                'type': personData.personNum,
                'imgUrl': personData.imgUrl,
            }
        });

//        router.back();

//        router.push({
//            uri: "pages/myList/myList",
//            params: {
//                'title': personData.name,
//                'type': personData.personNum,
//                'imgUrl': personData.imgUrl,
//            }
//        });
    },
    selectProfilePicture(){
        console.log("personPage=====choose:start")
        var context = featureAbility.getContext();
        var media = mediaLibrary.getMediaLibrary(context);
        let option = {
            type : "image",
            count : 1
        };
        media.startMediaSelect(option, (err, value) => {
            if (err) {
                console.info("personPage=====An error occurred when selecting media resources." + value);
                return;
            }
            let IMG_URL = value.toString();
            console.info("personPage=====Media resources selected." + IMG_URL);
            let file1 = { filename: this.$app.$def.uid +'-'+ IMG_URL, name: 'photo', uri: IMG_URL, type: "png" };
            console.info("personPage=====file1 : " + file1.toString());
            let imageId = this.guid();
            let data = { };
            console.info("personPage=====imageId:" + imageId);
            let header = { };
            let uploadTask;
            let myUrl = "http://" + this.$app.$def.ip +"/file/imgUpload?imgSignature=" + imageId + "&uid=" + this.$app.$def.uid
                            + "&imgType=profile";
            console.info("personPage=====myUrl:" + myUrl);
            let _this = this;
            request.upload(
                {
                    url: "http://" + this.$app.$def.ip +"/file/imgUpload?imgSignature=" + imageId + "&uid=" + this.$app.$def.uid
                            + "&imgType=profile",
                    header: header,
                    method: "POST",
                    files: [file1],
                    data: [data]
                }
            ).then((data) => {
                uploadTask = data;
                uploadTask.on('headerReceive', function callback(headers) {
                    console.info("personPage=====upOnHeader headers:" + JSON.stringify(headers));
                    _this.getProfileImg(_this.$app.$def.uid);
                });
            }).catch((err) => {
                console.error('personPage=====Failed to request the upload. Cause: ' + JSON.stringify(err));
            })
            console.info("personPage=====upload end");
        });
//        console.info("personPage=====choose:end");
    },
    guid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
    },
    getProfileImg(uid){
        let httpRequest = http.createHttp();
        console.info("personPage=====create http request to get profileImg Url");
        httpRequest.request(
            "http://" + this.$app.$def.ip + "/file/getProfileImg?uid=" + uid,
            {
                connectTimeout: 30000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            },(err, data) => {
            if (!err) {
                console.info("personPage=====Profile Img Result : " + data.result.toString());
                let value = JSON.parse(data.result.toString());
                this.person.imgUrl = "http://" + value.data;
            } else {
                console.info("personPage====> httpRequest err" + JSON.stringify(err));
                this.httpRequest.destroy();
            }
        }
        );
    }
}



